import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../res/colors.dart';
import '../../res/dimens.dart';
import '../../res/gaps.dart';
import '../../src/utils/theme_utils.dart';
import 'my_button.dart';

/// 自定义AppBar，支持左侧固定标题和右侧多按钮
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({
    super.key,
    this.backgroundColor,
    this.leftTitle = '', // 左侧固定标题（如"消息"）
    this.leftTitleOffset = 0.0, // 左侧标题水平偏移量
    this.leftTitleVerticalOffset = 0.0, // 左侧标题垂直偏移量
    this.leftTitleStyle, // 左侧标题样式
    this.title = '',
    this.titleStyle, // 原有标题样式
    this.centerTitle = '',
    this.backImg = 'images/ic_back_black.png',
    this.backImgColor,
    this.actionName = '',
    this.onPressed,
    this.isBack = true,
    // 下拉选项相关
    this.dropdownItems = const [],
    this.onDropdownChanged,
    this.selectedValue,
    // 下拉框样式配置
    this.dropdownWidth = 120,
    this.dropdownBackgroundColor = Colors.white,
    this.dropdownBorderRadius = 8.0,
    this.dropdownElevation = 4.0,
    this.dropdownItemHeight = 48.0,
    this.dropdownTextStyle,
    this.dropdownSelectedTextStyle,
    // 下拉框位置调整
    this.dropdownOffset = const Offset(0, 0),
    this.dropdownContentPadding = const EdgeInsets.symmetric(horizontal: 16),
    // 对齐方式配置
    this.buttonAlignment = MainAxisAlignment.end,
    this.contentAlignment = TextAlign.right,
    // 右侧按钮配置
    this.showRightButton = false,
    this.rightButtonType = RightButtonType.image,
    this.rightButtonText = '返回',
    this.rightButtonTextStyle,
    this.rightButtonImg = 'images/ic_back_black.png',
    this.rightButtonImgColor,
    this.onRightButtonPressed,
    this.rightButtonImgOffset = 0.0, // 右侧第一个按钮图标水平偏移
    this.rightButtonImgVerticalOffset = 0.0, // 新增：右侧第一个按钮图标垂直偏移
    this.rightButtonImgSize, // 新增：右侧第一个按钮图标大小
    // 新增：第二个右侧按钮配置
    this.showSecondRightButton = false,
    this.secondRightButtonType = RightButtonType.image,
    this.secondRightButtonText = '设置',
    this.secondRightButtonTextStyle,
    this.secondRightButtonImg = 'images/images/ic_settings.png',
    this.secondRightButtonImgColor,
    this.onSecondRightButtonPressed,
    this.secondRightButtonImgOffset = 0.0, // 右侧第二个按钮图标水平偏移
    this.secondRightButtonImgVerticalOffset = 0.0, // 新增：右侧第二个按钮图标垂直偏移
    this.secondRightButtonImgSize, // 新增：右侧第二个按钮图标大小
  });

  final Color? backgroundColor;
  final String leftTitle;
  final double leftTitleOffset;
  final double leftTitleVerticalOffset;
  final TextStyle? leftTitleStyle;
  final String title;
  final TextStyle? titleStyle;
  final String centerTitle;
  final String backImg;
  final Color? backImgColor;
  final String actionName;
  final VoidCallback? onPressed;
  final bool isBack;

  // 下拉选项数据
  final List<String> dropdownItems;
  final Function(String)? onDropdownChanged;
  final String? selectedValue;

  // 下拉框样式配置
  final double dropdownWidth;
  final Color dropdownBackgroundColor;
  final double dropdownBorderRadius;
  final double dropdownElevation;
  final double dropdownItemHeight;
  final TextStyle? dropdownTextStyle;
  final TextStyle? dropdownSelectedTextStyle;

  // 下拉框位置调整
  final Offset dropdownOffset;
  final EdgeInsetsGeometry dropdownContentPadding;

  // 对齐方式配置
  final MainAxisAlignment buttonAlignment;
  final TextAlign contentAlignment;

  // 右侧按钮配置
  final bool showRightButton;
  final RightButtonType rightButtonType;
  final String rightButtonText;
  final TextStyle? rightButtonTextStyle;
  final String rightButtonImg;
  final Color? rightButtonImgColor;
  final VoidCallback? onRightButtonPressed;
  final double rightButtonImgOffset;
  final double rightButtonImgVerticalOffset; // 新增属性
  final double? rightButtonImgSize; // 新增

  // 新增：第二个右侧按钮配置
  final bool showSecondRightButton;
  final RightButtonType secondRightButtonType;
  final String secondRightButtonText;
  final TextStyle? secondRightButtonTextStyle;
  final String secondRightButtonImg;
  final Color? secondRightButtonImgColor;
  final VoidCallback? onSecondRightButtonPressed;
  final double secondRightButtonImgOffset;
  final double secondRightButtonImgVerticalOffset; // 新增属性
  final double? secondRightButtonImgSize; // 新增

  @override
  Widget build(BuildContext context) {
    final Color bgColor = backgroundColor ?? context.backgroundColor;

    final SystemUiOverlayStyle overlayStyle = ThemeData.estimateBrightnessForColor(bgColor) == Brightness.dark
        ? ThemeUtils.light
        : ThemeUtils.dark;

    final Widget back = isBack
        ? IconButton(
      onPressed: () async {
        FocusManager.instance.primaryFocus?.unfocus();
        final isBack = await Navigator.maybePop(context);
        if (!isBack) {
          await SystemNavigator.pop();
        }
      },
      tooltip: 'Back',
      padding: const EdgeInsets.all(12.0),
      icon: Image.asset(
        backImg,
        color: backImgColor ?? ThemeUtils.getIconColor(context),
      ),
    )
        : Gaps.empty;

    // 左侧固定标题（如"消息"），支持自定义样式和偏移
    final Widget leftTitleWidget = leftTitle.isNotEmpty
        ? Positioned(
      left: isBack ? 48.0 + leftTitleOffset : 16.0 + leftTitleOffset,
      top: leftTitleVerticalOffset,
      bottom: -leftTitleVerticalOffset,
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          leftTitle,
          style: leftTitleStyle ?? const TextStyle(fontSize: Dimens.font_sp18),
        ),
      ),
    )
        : Gaps.empty;

    // 原有标题组件，支持自定义样式
    final Widget titleWidget = Semantics(
      namesRoute: true,
      header: true,
      child: Container(
        alignment: centerTitle.isEmpty ? Alignment.centerLeft : Alignment.center,
        width: double.infinity,
        margin: const EdgeInsets.symmetric(horizontal: 48.0),
        child: Text(
          title.isEmpty ? centerTitle : title,
          style: titleStyle ?? const TextStyle(fontSize: Dimens.font_sp18),
        ),
      ),
    );

    // 右侧第一个按钮
    final Widget rightButton = showRightButton
        ? rightButtonType == RightButtonType.image
        ? Transform.translate(
      // 同时应用水平和垂直偏移
      offset: Offset(-rightButtonImgOffset, -rightButtonImgVerticalOffset),
      child: IconButton(
        onPressed: onRightButtonPressed ?? (() => Navigator.maybePop(context)),
        tooltip: rightButtonText,
        padding: const EdgeInsets.all(12.0),
        icon: Image.asset(
          rightButtonImg,
          color: rightButtonImgColor ?? ThemeUtils.getIconColor(context),
          width: rightButtonImgSize,
          height: rightButtonImgSize,
        ),
      ),
    )
        : TextButton(
      onPressed: onRightButtonPressed ?? (() => Navigator.maybePop(context)),
      child: Text(
        rightButtonText,
        style: rightButtonTextStyle ??
            TextStyle(
              color: context.isDark ? Colours.dark_text : Colours.text,
              fontSize: Dimens.font_sp14,
            ),
      ),
    )
        : Gaps.empty;

    // 右侧第二个按钮
    final Widget secondRightButton = showSecondRightButton
        ? secondRightButtonType == RightButtonType.image
        ? Transform.translate(
      // 同时应用水平和垂直偏移
      offset: Offset(-secondRightButtonImgOffset, -secondRightButtonImgVerticalOffset),
      child: IconButton(
        onPressed: onSecondRightButtonPressed ?? (() => Navigator.maybePop(context)),
        tooltip: secondRightButtonText,
        padding: const EdgeInsets.all(12.0),
        icon: Image.asset(
          secondRightButtonImg,
          color: secondRightButtonImgColor ?? ThemeUtils.getIconColor(context),
          width: secondRightButtonImgSize,
          height: secondRightButtonImgSize,
        ),
      ),
    )
        : TextButton(
      onPressed: onSecondRightButtonPressed ?? (() => Navigator.maybePop(context)),
      child: Text(
        secondRightButtonText,
        style: secondRightButtonTextStyle ??
            TextStyle(
              color: context.isDark ? Colours.dark_text : Colours.text,
              fontSize: Dimens.font_sp14,
            ),
      ),
    )
        : Gaps.empty;

    // 构建右侧下拉选择按钮
    Widget buildDropdownButton() {
      if (dropdownItems.isEmpty) return Gaps.empty;

      return Positioned(
        right: (showRightButton ? 48.0 : 0) + (showSecondRightButton ? 48.0 : 0),
        child: Theme(
          data: Theme.of(context).copyWith(
            popupMenuTheme: PopupMenuThemeData(
              color: dropdownBackgroundColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(dropdownBorderRadius),
              ),
              elevation: dropdownElevation,
            ),
          ),
          child: _CustomPopupMenuButton<String>(
            offset: dropdownOffset,
            buttonText: selectedValue ?? '请选择',
            textStyle: TextStyle(
              color: context.isDark ? Colours.dark_text : Colours.text,
              fontSize: Dimens.font_sp14,
            ),
            buttonAlignment: buttonAlignment,
            itemBuilder: (BuildContext context) {
              return dropdownItems.map((item) {
                final bool isSelected = item == selectedValue;
                return PopupMenuItem<String>(
                  value: item,
                  height: dropdownItemHeight,
                  padding: EdgeInsets.zero,
                  child: Container(
                    padding: dropdownContentPadding,
                    child: Row(
                      mainAxisAlignment: buttonAlignment,
                      children: [
                        if (isSelected)
                          Icon(Icons.check,
                              color: dropdownSelectedTextStyle?.color ?? Colors.blue, size: 16),
                        if (isSelected) const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            item,
                            textAlign: contentAlignment,
                            style: isSelected
                                ? dropdownSelectedTextStyle ??
                                TextStyle(color: Colors.blue, fontWeight: FontWeight.bold)
                                : dropdownTextStyle ??
                                TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }).toList();
            },
            onSelected: (value) {
              _callApiBeforeChange(value);
              onDropdownChanged?.call(value);
            },
          ),
        ),
      );
    }

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: overlayStyle,
      child: Material(
        color: bgColor,
        child: SafeArea(
          child: Stack(
            alignment: Alignment.centerLeft,
            children: <Widget>[
              // 原有标题（居中或自定义对齐）
              titleWidget,
              // 左侧固定标题（如"消息"）
              leftTitleWidget,
              // 返回按钮
              back,
              // 右侧按钮区域
              Positioned(
                right: 0.0,
                child: Row(
                  children: [
                    buildDropdownButton(),
                    secondRightButton,
                    rightButton,
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _callApiBeforeChange(String value) {
    print('调用接口获取 $value 的数据');
  }

  @override
  Size get preferredSize => const Size.fromHeight(48.0);
}

/// 右侧按钮类型
enum RightButtonType {
  image, // 图片按钮
  text, // 文字按钮
}

/// 自定义PopupMenuButton，支持更精确的位置控制
class _CustomPopupMenuButton<T> extends StatefulWidget {
  final Offset offset;
  final String buttonText;
  final TextStyle textStyle;
  final MainAxisAlignment buttonAlignment; // 按钮对齐方式
  final PopupMenuItemBuilder<T> itemBuilder;
  final ValueChanged<T>? onSelected;

  const _CustomPopupMenuButton({
    required this.offset,
    required this.buttonText,
    required this.textStyle,
    required this.buttonAlignment,
    required this.itemBuilder,
    this.onSelected,
  });

  @override
  State<_CustomPopupMenuButton<T>> createState() => _CustomPopupMenuButtonState<T>();
}

class _CustomPopupMenuButtonState<T> extends State<_CustomPopupMenuButton<T>> {
  final GlobalKey _buttonKey = GlobalKey();

  void _showMenu() {
    final RenderBox buttonBox = _buttonKey.currentContext!.findRenderObject() as RenderBox;
    final Size buttonSize = buttonBox.size;
    final Offset buttonPosition = buttonBox.localToGlobal(Offset.zero);

    // 计算弹出菜单的位置（右对齐，正下方）
    final double left = buttonPosition.dx;
    final double top = buttonPosition.dy + buttonSize.height + widget.offset.dy;
    final double right = left + buttonSize.width;

    final List<PopupMenuEntry<T>> items = widget.itemBuilder(context);
    if (items.isEmpty) return;

    showMenu<T>(
      context: context,
      position: RelativeRect.fromLTRB(left, top, right, top),
      items: items,
      elevation: widget.offset.dx, // 使用offset的x值作为elevation微调
    ).then((T? selectedValue) {
      if (selectedValue != null && widget.onSelected != null) {
        widget.onSelected!(selectedValue);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      key: _buttonKey,
      child: GestureDetector(
        onTap: _showMenu,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Row(
            mainAxisAlignment: widget.buttonAlignment, // 设置按钮内容对齐方式
            children: [
              Text(
                widget.buttonText,
                style: widget.textStyle,
              ),
              const Icon(Icons.arrow_drop_down, size: 18),
            ],
          ),
        ),
      ),
    );
  }
}